<?php
class BlogController extends  Controller{


	public function index($param){
		$this->getSmarty();
		require_once COMMON . DS  . 'Constant.class.php';
		$paramdata->key = $param['key'];
		$paramdata->type = $param['type'];
		$this->smarty->assign ( 'paramdata', $paramdata );

        $this->smarty->assign ( 'pagesets', Constant::indexHeader() );
		$this->smarty->assign ( 'blogcats', Constant::getCategorylist() );
		$this->smarty->display("blog.tpl");
	}
	
	public function getBlogList() {
		$this->getSmarty();
		$pnum = 6;
		require_once SERVICE . DS . 'PostService.class.php';
		$service = new PostService ( $this->getDB () );
		
		$table = 'posts'; 
		require_once SERVICE.DS."CommonLogicService.class.php";
		$common = new CommonLogicService($this->getDB());
	    $page = isset ( $_POST ['page'] ) ? intval ( $_POST ['page'] ) : 1;
		$rows = isset ( $_POST ['rows'] ) ? intval ( $_POST ['rows'] ) : 6;
		$offset = ($page - 1) * $rows;
		$result = array ();
		$row_count = $common->countNum($table);
		$result ["total"] = ceil($row_count/$rows);
		$result ["records"] = $row_count;
		$result ["page"] = $page;
		
		
		$wherekey = null;
		if($_POST['key']){
			$wherekey = ' where p.post_title like "%'.$_POST['key'].'%"';
		}
		if($_POST['type']){
			if($wherekey == null){
				$wherekey = ' where c.category_name = "'.$_POST['type'].'"';
			}else{
				$wherekey.=  ' and c.category_name = "'.$_POST['type'].'"';
			}
			
		}
		
		$datasql = " SELECT p.*,c.category_name FROM posts p LEFT JOIN post_category c ON p.post_category = c.category_id $wherekey LIMIT $offset,$rows ";
		
		//print($datasql);
		$blog_lists = $common->getResults($datasql);
		foreach ($blog_lists as $k => $blog) {
			$p_content = strip_tags($blog->post_content);
			if(strlen($p_content) > 400){
				$p_content = substr($p_content,0,400);
				$p_content = $p_content.".....";
			}
			$result_bloglist[] = array (
					"post_author" => $blog->post_author,
					"post_date" => $blog->post_date,
					"post_content" => $p_content,
					"post_file_location" => $blog->post_file_location,
					"category_name" => $blog->category_name,
					"post_title" => $blog->post_title,
					"category_url" => WEBSITE_URL."blog".DS."index?type=".$blog->category_name,
					"post_url" => WEBSITE_URL."post".DS."index?id=".$blog->ID
					 
			 );
		}
		$result['normal'] = $_POST['normal'];
		$result['key'] = $_POST['key'];
		$result ["rows"] = $result_bloglist;
		echo json_encode ( $result );
	}

}